package com.xxx.DAO;

import com.xxx.entity.Comment;
import com.xxx.util.JDBCUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class commentDao {

    SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private JDBCUtil util = new JDBCUtil();
    int i=0;

    //增加一条数据
    public int add(String uName,String contest,String uIden){
        if (uIden.equals("admin")){i=1;}
        String sql = "insert into contest (uName,contest,createDate,type) values(?,?,?,?)";
        int result = 0;
        PreparedStatement ps = util.createPstmt(sql);
        String creatDate=format.format(new Date());
        try {
            ps.setString(1, uName);
            ps.setString(2, contest);
            ps.setString(3, creatDate);
            ps.setInt(4, i);
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            util.close();
        }
        return result;
    }

    //删除一条数据(不用用到吧应该)
    public int delete(String cid){
        String sql="delete from contest where cid=?";
        int result=0;
        PreparedStatement ps=util.createPstmt(sql);
        try {
            ps.setString(1,cid);
            result=ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            util.close();
        }
        return result;
    }

    //查询所有数据
    public List findAll(){
        String sql="select * from contest order by id desc";
        ResultSet rs=null;
        PreparedStatement ps=util.createPstmt(sql);
        List list=new ArrayList();
        try {
            rs=ps.executeQuery();
            while (rs.next()){
                int id=rs.getInt("id");
                String uName=rs.getString("uName");
                String contest=rs.getString("contest");
                String createDate=rs.getString("createDate");
                int type=rs.getInt("type");
                String time=null;
                try {
                    Long date1=format.parse(format.format(new Date())).getTime();//获取当前时间的毫秒数
                    Long date2=format.parse(rs.getString("createDate")).getTime();
                    if (date1-date2<=60000){time="刚刚";}
                    else if (date1-date2>60000&&date1-date2<=300000){time="五分钟前";}
                    else{time=rs.getNString("createDate");}
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                    Comment comment=new Comment(uName,contest,createDate,type,time);
                    list.add(comment);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            util.close(rs);
        }
        return list;
    }
}
